<template>
  <el-form ref="skuFormRef" label-width="100px" :rules="skuFormRules" :model="skuInfo">
    <el-form-item label="SPU名称">
      <span>{{ props.currentSpuInfo.spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称">
      <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input-number
        class="mx-4"
        style="width: 100%"
        v-model="skuInfo.price"
        :min="1"
        :max="10"
        controls-position="right"
      />
    </el-form-item>
    <el-form-item label="重量(千克)">
      <el-input-number
      v-model="skuInfo.weight"
        style="width: 100%"
        class="mx-4"
        :min="1"
        :max="10"
        controls-position="right"
      />
    </el-form-item>
    <el-form-item label="规格描述">
      <el-input type="textarea" rows="4" v-model="skuInfo.skuDesc" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col :md="12" :sm="12" :xs="24" :lg="8" v-for="(attr,index) in attrList" :key="attr.id">
          <el-form-item :label="attr.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]" @change="clearAttrRules">
              <el-option :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`" :label="attrValue.valueName" :key="attrValue.id"  v-for="attrValue in attr.attrValueList"/>
           
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="12" :sm="12" :xs="24" :lg="8">
          <el-form-item label="电池容量">
            <el-select>
              <el-option value="one" />
              <el-option value="two" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="12" :sm="12" :xs="24" :lg="8">
          <el-form-item label="手机相素">
            <el-select>
              <el-option value="one" />
              <el-option value="two" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="12" :sm="12" :xs="24" :lg="8">
          <el-form-item label="机身内存">
            <el-select>
              <el-option value="one" />
              <el-option value="two" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" v-model="skuInfo.skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col :md="12" :sm="12" :xs="24" :lg="8" v-for="saleAttr in spuSaleAttrList" :key="saleAttr.id">
          <el-form-item :label="saleAttr.saleAttrName">
            <el-select v-model="skuInfo.skuSaleAttrValueList" @change="clearAttrRules">
              <el-option v-for="saleAttrValue in saleAttr.spuSaleAttrValueList" :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`" :label="saleAttrValue.saleAttrValueName" :key="saleAttrValue.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="12" :sm="12" :xs="24" :lg="8">
          <el-form-item label="电池容量">
            <el-select>
              <el-option value="服务器没提供数据" />
             
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" align="center" prop="skuImageList">
      <el-table border style="margin-bottom:10px" :data="spuImageList" @imgchange="handleSelectionChange">
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="图片">
          <template v-slot="{row,$index}">
            <el-image :src="row.imgUrl" :alt="row.imgName" style="width: 100px; height: 100px;"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="名称"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button v-if="row.isDefault==='0'" type="primary" @click="toSetDefaultImg(row)">设置为默认图片</el-button>
            <el-button v-else type="success">默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="submitSkuForm(skuFormRef)">保存</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "SkuForm",
});
</script>

<script lang="ts" setup>
import { ElMessage, type FormRules } from 'element-plus';
import { ref,onMounted ,reactive} from "vue";
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from "@/api/product/spu";
import { reqGetAttrListData } from "@/api/product/attr";
import { useCategoryListStore } from '@/stores/categorySelector';
import {reqSaveSkuInfo,reqGetSkuListData} from '@/api/product/sku'

const num = ref(0);
const weight = ref(0)
const categoryStore = useCategoryListStore()
//获取照片列表
const spuImageList = ref([])
//spu基础属性列表
const spuSaleAttrList = ref([])
//平台属性列表
const attrList = ref([])
const skuInfo = reactive({
  category3Id:0,
  // spu名称
  skuName: '',
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: '',
  // 默认图片
  skuDefaultImg: '',
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: []
})
const props = defineProps<{
  currentSpuInfo
}>();
const emits = defineEmits
const skuFormRef = ref([])
onMounted(async()=>{
  const id = props.currentSpuInfo.id
  const [resSpuImageList,resSpuSaleAttrList,resAttrList] = await Promise.allSettled([reqGetSpuImageList(id),reqGetSpuSaleAttrList(id),reqGetAttrListData({
    category1Id:categoryStore.category1Id as number,
    category2Id:categoryStore.category2Id as number,
    category3Id:categoryStore.category3Id as number
  })])
  if(resSpuImageList.status ==='fulfilled'){
    spuImageList.value =resSpuImageList.value.map(item=>{
      return {
        ...item,
        isDefault:'0'
      }
    })
  }
  if(resSpuSaleAttrList.status ==='fulfilled'){
    spuSaleAttrList.value =resSpuSaleAttrList.value
  }
  if(resAttrList.status ==='fulfilled'){
    attrList.value =resAttrList.value
  }
})

const skuAttrValueListValidator = (rule: any, value: any, callback: any) => {
  // console.log('rr', rule, value, callback);
  // rule 表示一种校验规则对象
  // value 表示要校验的数据值 有可能是对象有可能是数组
  // callback是执行函数
  if (!value.length) {
    return callback(new Error('请至少选择一个平台属性...'));
  }

  // 如果上面的条件成立(也就是选择了至少一个平台属性),此时才会走下面的调用
  callback(); // 里面的参数为空,调用一下，表示通过校验
};
const skuImageListdata = (rule: any, value: any, callback: any) => {
  // console.log('rr', rule, value, callback);
  // rule 表示一种校验规则对象
  // value 表示要校验的数据值 有可能是对象有可能是数组
  // callback是执行函数
  if (value.length<3) {
    return callback(new Error('请至少选择3图片属性...'));
  }

  // 如果上面的条件成立(也就是选择了至少一个平台属性),此时才会走下面的调用
  callback(); // 里面的参数为空,调用一下，表示通过校验
};
const skuFormRules = reactive<FormRules>({
  skuName: [
    { required: true, message: '请输入sku名称', trigger: 'blur' },
    { min: 1, max: 10, message: 'sku名称应该是在1到10之间', trigger: 'blur' }
  ],
  price: [{ required: true, message: '添加价格', trigger: 'change' }],
  weight: [{ required: true, message: '请添加重量', trigger: 'change' }],
  skuDesc: [{ required: true, message: '请添加sku描述', trigger: 'blur' }],
  skuSaleAttrValueList: [
    {
      required: true,
      message: '请至少选择一个销售属性',
      trigger: 'change',
      type: 'array'
    }
  ],
  skuAttrValueList: [{ required: true, validator: skuAttrValueListValidator, trigger: 'blur' }],
  skuImageList:[{ required: true, validator: skuImageListdata, trigger: 'blur' }]

});


const toSetDefaultImg =(row)=>{
  spuImageList.value.forEach(item=>{
    item.isDefault = '0'
  })
  row.isDefault = '1'
}
const handleSelectionChange = (val)=>{
  skuInfo.skuImageList = val
}

//保存按钮发给服务器的函数
const submitSkuForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      const skuImg = skuInfo.skuImageList.find(item => item.imgUrl === skuInfo.skuDefaultImg);
      if (!skuImg) return ElMessage.error('请在所选图片中指定默认图片');
      // 处理平台属性 将为undefined的清除掉
      skuInfo.skuAttrValueList = attrValueList.value.filter(Boolean).map(item => {
        const [attrId, attrName, valueId, valueName] = item.split(':');
        return {
          attrId,
          attrName,
          valueId,
          valueName
        };
      });

      // 销售属性也要统一处理一下
      skuInfo.skuSaleAttrValueList = spuSaleAttrValueList.value.filter(Boolean).map(item => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':');
        return {
          saleAttrId,
          saleAttrName,
          saleAttrValueId,
          saleAttrValueName
        };
      });
      skuInfo.category3Id = categoryStore.category3Id as number;
      skuInfo.spuId = props.currentSpuInfo.id as number;

      await reqSaveSkuInfo(skuInfo);
      ElMessage.success('添加sku成功了...');
      emits('changeStatus', ShowStatus.SPU_LIST);
    } else {
      console.log('error submit!');
      return false;
    }
  });
};

</script>

<style scoped>
</style>